<template>
  <!-- 增加加载状态和错误处理 -->
  <div v-if="loading" class="loading-container">
    <van-loading type="spinner" size="30px"/>
  </div>

  <div v-else-if="error" class="error-container">
    <van-empty description="获取队伍信息失败"/>
  </div>

  <div v-else>
    <div class="teamShow-Container">
      <van-card
          style="margin: 2px"
      >
        <template #title>
          <div class="team-title">{{ team.name }}</div>
        </template>
        <template #thumb>
          <van-image
              :src="chunWuTeam" height="100%" width="80%"
          />
        </template>
        <template #tags>
          <van-tag plain type="danger" style="margin-right: 4px; margin-top: 4px">
            {{ teamStatusEnum[team.status] }}
          </van-tag>
        </template>
        <template #bottom>
          <div style="margin: 2px 0;">
            {{ `人数:${team.hasJoinNum} / ${team.maxNum}` }}
          </div>
        </template>
      </van-card>
    </div>

    <!-- 队伍其他信息展示 -->
    <van-cell-group style="margin: 10px 0;">
      <van-cell title="队伍描述" :value="team.description || '未知'"/>
      <van-cell title="状态" :value="teamStatusEnum[team.status] || '未知'"/>
      <van-cell title="队长" is-link @click="() => {toShowUserInfo(team.user?.id)}"/>
      <van-cell title="小队成员" is-link @click="() => {doShowUserListInfo()}"/>
      <van-cell title="当前加入人数" :value="team.hasJoinNum || '未知'"/>
      <van-cell title="创建时间" :value="formatTime(team.createTime?.toString()) || '未知'"/>
      <van-cell title="过期时间" :value="formatTime(team.expireTime?.toString()) || '未知'"/>
    </van-cell-group>

    <!-- 成员列表对话框（通过v-if控制显示） -->
    <!-- 隐藏确认按钮，只保留关闭 -->
    <van-dialog
        v-model:show="isShowTeamListDialog"
        title="小队成员"
        show-cancel-button
        cancel-text="关闭"
        confirm-button-style="display: none"
    >
      <!-- 自定义对话框内容：成员列表 -->
      <template #default>
        <div class="member-list">
          <!-- 无成员时显示空状态 -->
          <van-empty description="暂无成员" v-if="!team.teamUserList || team.teamUserList.length === 0"/>

          <!-- 有成员时展示网格列表 -->
          <van-grid column-num="2" :border="false" v-else>
            <van-grid-item v-for="(user, index) in team.teamUserList" :key="index" class="member-item">
              <!-- 头像 -->
              <van-image
                  :src="user.avatarUrl || defaultAvatar"
                  class="member-avatar"
                  width="50%"
                  round
              />
              <!-- 用户名 -->
              <div class="member-name">{{ user.username || '未知用户' }}</div>
              <!-- 性别 -->
              <div class="member-gender">
                {{ Number(user.gender) === 0 ? '男' : '女' }}
              </div>
            </van-grid-item>
          </van-grid>
        </div>
      </template>
    </van-dialog>

    <!-- 操作按钮 -->
    <div class="button-container">

    </div>
  </div>
</template>
w

<script setup lang="ts">
import {ref, onMounted} from 'vue';
import {getTeamById} from '../../api/team.ts';

import {showFailToast, showDialog} from 'vant';
import {useRoute, useRouter,} from "vue-router";
import type {TeamType} from "../../models/Team";
import chunWuTeam from "../../assets/chunWuTeam.jpg";
import {teamStatusEnum} from "../../constants/TeamStatus.ts";
import type {UserType} from "../../models/User";

const route = useRoute();
const router = useRouter();

const team = ref<TeamType>({} as TeamType);
const loading = ref(true);
const error = ref(false);
const isShowTeamListDialog = ref(false);
const defaultAvatar = ref('https://javawebprogram.oss-cn-beijing.aliyuncs.com/2025/07/96e4337a-ca4d-49bf-be07-43bd3af88f90.webp');

// TODO 获取当前队伍人数
/**
 * 获取队伍信息
 */
onMounted(async () => {
  loading.value = true;
  error.value = false;

  // 正确获取并验证teamId
  const teamIdStr = route.query.id as string;
  if (!teamIdStr || isNaN(Number(teamIdStr))) {
    showFailToast('队伍加载错误');
    error.value = true;
    loading.value = false;
    return;
  }
  // 转化teamId为数字
  const teamId = Number(teamIdStr);

  try {
    const result = await getTeamById(teamId);
    team.value = result.data;

  } catch (err) {
    console.error('获取队伍信息失败', err);
    showFailToast('获取队伍信息失败');
    error.value = true;
  } finally {
    loading.value = false;
  }
});

// 跳转到用户详细信息
const toShowUserInfo = (userId: number) => {
  router.push({
    path: '/user/showInfo',
    query: {
      userId: userId,
    }
  })
};

// 弹出对话框显示小队成员信息列表
const doShowUserListInfo = () => {
   isShowTeamListDialog.value = true;
}

/**
 * 时间格式化函数：将 ISO 时间（如 2025-07-08T15:41:35）转换为 yyyy-MM-dd
 * @param time 原始时间字符串（支持 ISO 格式或时间戳）
 * @returns 格式化后的日期字符串，无效时间返回 null
 */
const formatTime = (time: string | undefined): string | null => {
  if (!time) return null; // 时间为空直接返回null
  try {
    const date = new Date(time); // 解析时间字符串
    // 获取年、月、日（月份从0开始，需+1）
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 补0确保两位数
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (err) {
    console.error('时间格式化失败', err);
    return null; // 解析失败返回null
  }
};


</script>

<style scoped>
.loading-container, .error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.button-container {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  gap: 16px;
}

.team-title {
  margin: 6px 0;
  font-size: 20px;
  font-weight: bold;
}

.teamShow-Container {
  margin: 4px;
}

</style>